/**
 * @author Created by qiush on 2017-07-12.
 */

const path = require('path');
const {app, ipcMain, BrowserWindow} = require('electron');

const fileUtil = require('./fileUtil');
const dialogUtil = require('./dialogUtil');

const configFile = path.join(app.getPath('userData'), 'config.json');

const configUtil = {
  async loadConfig() {
    const configContent = await fileUtil.readFile(configFile);
    return JSON.parse(configContent);
  },

  async saveConfig(config) {
    return await fileUtil.writeFile(configFile, config);
  }
};

ipcMain.on('save-config', (event, config) => {
  const configWindow = BrowserWindow.fromWebContents(event.sender);

  configUtil.saveConfig(config)
    .then(() => {
      return dialogUtil.showMessage(configWindow, '配置已保存成功!');
    })
    .then(() => {
      configWindow.close();
    })
    .catch(dialogUtil.showError)
});

module.exports = configUtil;
